package com.wangyadong.hobby.concurrent;

import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;

import static com.wangyadong.hobby.concurrent.CountDownLatchDemo.PRINT_CONSUMER;

public class PhaserDemo2 {
    private static final int num = 10;
//    private static final Phaser phaser = new Phaser(num + 1);

    public static void main(String[] args) throws InterruptedException {
        Phaser phaser = new MyPhaser();
        for (int i = 0; i < num; i++) {
            Thread thread = new Thread(() -> {
                try {
                    phaser.register();
                    PRINT_CONSUMER.accept("--------------子任务开始执行----------------");
                    TimeUnit.SECONDS.sleep(2);
                    PRINT_CONSUMER.accept("--------------子任务开始执行完毕-------------");
                    phaser.arriveAndAwaitAdvance();
                } catch (InterruptedException e) {
                    PRINT_CONSUMER.accept("--------------发生异常----------------");
                }
            });
            thread.start();
        }
        TimeUnit.SECONDS.sleep(0x4);
        PRINT_CONSUMER.accept(" 结束");
    }

    public static class MyPhaser extends Phaser {
        @Override
        protected boolean onAdvance(int phase, int registeredParties) {
            PRINT_CONSUMER.accept("到达----");
//            return super.onAdvance(phase, registeredParties);
            return false;
        }
    }
}
